package com.eva.databuilder.builders.cms;

import com.eva.cms.biz.category.CmsCategoryBiz;
import com.eva.cms.biz.category.vo.CmsCategoryNodeVO;
import com.eva.databuilder.bo.TemplateDataParameters;
import com.eva.dao.cms.model.CmsTemplate;
import com.eva.framework.cache.autowired.Cache;
import com.eva.service.cms.CmsTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 构建栏目树数据
 */
@Slf4j
@Component
public class CategoryTreeBuilder extends BaseCategoryTreeBuilder {

    @Resource
    private CmsCategoryBiz cmsCategoryBiz;

    @Resource
    private CmsTemplateService cmsTemplateService;

    @Override
    // 永久缓存，后台操作栏目时会清理此缓存
    @Cache("CATEGORIES_TREE")
    public List<CmsCategoryNodeVO> build(TemplateDataParameters parameters) {
        List<CmsCategoryNodeVO> nodes = cmsCategoryBiz.findTree(Boolean.FALSE);
        // 获取栏目模板ID集合
        Set<Integer> templateIds = new HashSet<>();
        this.getTemplateIds(nodes, templateIds);
        // 查询模板并根据ID进行分组
        Map<Integer, CmsTemplate> cmsTemplateMap = cmsTemplateService.findByIds(templateIds)
                .stream()
                .collect(Collectors.toMap(CmsTemplate::getId, cmsTemplate -> cmsTemplate));
        // 补充常规栏目的uri
        this.paddingCategoryUri(nodes, cmsTemplateMap);
        // 编译栏目的uri
        this.compileCategoryUri(nodes, parameters);
        return nodes;
    }
}
